package com.any.hook.core.webapi.api;

import com.any.hook.common.exception.HookException;
import com.any.hook.core.webapi.config.Init;
import com.any.hook.core.webapi.config.WebApiErrorCode;
import com.any.hook.core.webapi.entity.DBInfo;
import com.any.hook.core.webapi.entity.Result;
import com.any.hook.core.webapi.service.EtlJsonService;
import com.any.hook.core.webapi.util.ExceptionTracker;
import com.any.hook.core.webapi.util.GenSqlUtil;
import com.any.hook.core.webapi.util.LoadDriver;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@Controller
public class EtlJsonController {
    @Autowired
    private EtlJsonService etlJsonService;
    @GetMapping("/db/findall/")
    @ResponseBody
    public Result getAll(){
        try{
            List<DBInfo> allName=etlJsonService.getAllName();
            if(allName==null || allName.size()==0 || allName.get(0)==null){
                throw HookException.asHookException(WebApiErrorCode.API_JSON_LOGIC_ERROR,
                        "查询不到数据库连接的任何信息，请添加数据库连接 .");
            }
            return Result.SUSSRESULT(allName);
        }catch (Exception e){
            String message;
            if(e instanceof  HookException){
                message= ExceptionTracker.trace(e);
            }else {
                message=ExceptionTracker.trace(HookException.asHookException(WebApiErrorCode.API_RUNTIME_ERROR,e.getCause()));
            }
            if(Init.IS_DEBUG){
                e.printStackTrace();
            }
            e.printStackTrace();
            return Result.ERRORRESULT(message);
        }
    }
    @GetMapping("/db/tables/{name}")
        @ResponseBody
        public Result getTbNames(@PathVariable String name) throws SQLException {
            if(StringUtils.isBlank(name)){
                throw HookException.asHookException(WebApiErrorCode.API_JOB_PARAM_CHECKERROR,
                        "参数检查错误请检查URL是否正确 .");
            }
            DBInfo dbInfo=etlJsonService.getDbInfoByName(name);
            if(dbInfo == null){
                throw HookException.asHookException(WebApiErrorCode.API_JSON_LOGIC_ERROR,
                        "数据出现问题请联系开发人员 .");
            }
            LoadDriver.loadDriver(dbInfo.getDriverUrl());
            Statement statement=null;
            ResultSet rs=null;
            try (Connection connection = DriverManager.getConnection(DBInfo.getFullDriverUrl(dbInfo), dbInfo.getUser(), dbInfo.getPassword());) {
                if (connection != null && connection.isValid(1000)) {
                    statement=connection.createStatement();
                    statement.execute(GenSqlUtil.genGenTablesSql(dbInfo));
                    rs=statement.getResultSet();
                    List<String> tables=new ArrayList<>();
                    while (rs.next()){
                        tables.add(rs.getString(1));
                    }
                    statement.close();
                    rs.close();
                    return Result.SUSSRESULT(tables);
                } else {
                    return Result.ERRORRESULT("数据库连接是无效的！请重新配置");
                }
            } catch (Exception e) {
                if(statement!=null ){
                    statement.close();
                }
                if(rs!=null){
                    rs.close();
                }
                if(Init.IS_DEBUG){
                    e.printStackTrace();
                }
                return Result.ERRORRESULT(e.getMessage());
            } finally {

            }
    }
    @GetMapping("/db/column/{name}/{tname}")
    @ResponseBody
    public Result getColumn(@PathVariable String name,@PathVariable String tname) throws SQLException {
        if(StringUtils.isBlank(name)||StringUtils.isBlank(tname)){
            throw HookException.asHookException(WebApiErrorCode.API_JOB_PARAM_CHECKERROR,
                    "参数检查错误请检查URL是否正确 .");
        }
        DBInfo dbInfo=etlJsonService.getDbInfoByName(name);
        if(dbInfo == null){
            throw HookException.asHookException(WebApiErrorCode.API_JSON_LOGIC_ERROR,
                    "数据出现问题请联系开发人员 .");
        }
        LoadDriver.loadDriver(dbInfo.getDriverUrl());
        Statement statement=null;
        ResultSet rs=null;
        try (Connection connection = DriverManager.getConnection(DBInfo.getFullDriverUrl(dbInfo), dbInfo.getUser(), dbInfo.getPassword());) {
            if (connection != null && connection.isValid(1000)) {
                statement=connection.createStatement();
                statement.execute(GenSqlUtil.genGenColSql(dbInfo,tname));
                rs=statement.getResultSet();
                List<String> tables=new ArrayList<>();
                while (rs.next()){
                    tables.add(rs.getString(1));
                }
                statement.close();
                rs.close();
                return Result.SUSSRESULT(tables);
            } else {
                return Result.ERRORRESULT("数据库连接是无效的！请重新配置");
            }
        } catch (Exception e) {
            if(statement!=null ){
                statement.close();
            }
            if(rs!=null){
                rs.close();
            }
            if(Init.IS_DEBUG){
                e.printStackTrace();
            }
            return Result.ERRORRESULT(e.getMessage());
        } finally {

        }
    }
}
